package com.WISSC.controller;


import com.WISSC.bean.*;
import com.WISSC.bean.layuiBean.ResultPage;
import com.WISSC.commen.BaseController;
import com.WISSC.service.AuthorizationImageService;
import com.WISSC.service.AuthorizationService;
import com.WISSC.service.ConfigureService;
import com.WISSC.service.WebPageService;
import com.WISSC.util.Respons.ResponseUtil;
import com.WISSC.util.date.DateUtil;
import com.WISSC.util.file.FileUpload;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.WISSC.util.file.FileUpload;

import java.io.FileNotFoundException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 授权机构信息表 前端控制器
 * </p>
 *
 * @author 张凯
 * @since 2019-05-06
 */
@Controller
@RequestMapping("/authorization")
@Api(value = "授权机构 controller", tags = "授权机构")
public class AuthorizationController extends BaseController {

    @Autowired
    AuthorizationService authorizationService;
    @Autowired
    AuthorizationImageService authorizationImageService;
    @Autowired
    WebPageService webPageService;
    @Autowired
    ConfigureService configureService;

    //跳转首页
    @RequestMapping(value = "main.html", method = RequestMethod.GET)
    public String main() {
        return "main/authorization";
    }

    //跳转添加页面
    @RequestMapping(value = "authorization_add.html", method = RequestMethod.GET)
    public String authorization_add() {
        return "add/authorization_add";
    }

    //跳转编辑页面
    @RequestMapping(value = "authorization_edit.html", method = RequestMethod.GET)
    public String authorization_edit(Long id, Model model, String url) {
        model.addAttribute("id", id);
        model.addAttribute("url", url);
        return "edit/authorization_edit";
    }

    @RequestMapping(value = "shou.html", method = RequestMethod.GET)
    public String shou() {
        return "shou";
    }

    //跳转查询页
    @RequestMapping(value = "selectById.html", method = RequestMethod.GET)
    public String authorization_select() {
        return "authorization/selectById";
    }

    //跳转机构信息查询页面
    @RequestMapping(value = "authorization_select.html", method = RequestMethod.GET)
    public String authorization(Model model, Authorization authorization) {
        model.addAttribute("unitName", authorization.getUnitName());
        return "authorization/authorization_select";
    }

    //机构查询登陆页面
    @RequestMapping(value = "authorization_login.html", method = RequestMethod.GET)
    public String student_login() {
        return "authorization_login";
    }

    //机构查询首页
    @RequestMapping(value = "authorization_index.html", method = RequestMethod.GET)
    public String authorization_index(Model model, Authorization authorization) {
        model.addAttribute("unitName", authorization.getUnitName());
        model.addAttribute("list", webPageService.selectAll());
        model.addAttribute("url",configureService.getById(1).getConfigure());
        return "authorization_index";
    }

    /**
     * @param file
     * @return 多文件上传 配合添加使用
     * @throws Exception
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Massage upload(@RequestParam("file") MultipartFile file) {
        return authorizationImageService.upload(file);
    }

    /**
     * @param param
     * @param pIds
     * @return 机构信息添加添加
     */
    @RequestMapping(value = "authorizationInsert", method = RequestMethod.POST)
    @ResponseBody
    public String authorizationInsert(String param, String[] pIds, HttpSession session) {
        Authorization authorization = JSONObject.parseObject(param, Authorization.class);
        if (getUser(session).getStatus() == 2) {
            authorization.setType(1);
            authorization.setFlag(4);
        } else {
            authorization.setType(2);
            authorization.setFlag(1);
        }
        return authorizationService.authorizationInsert(authorization, pIds);

    }

    /**
     * @param page
     * @param limit
     * @param unitName
     * @param startTime
     * @param city
     * @param grantType
     * @param grantLevel
     * @return 查询 + 分页
     */
    @RequestMapping(value = "selectMyPage", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<Authorization> selectMyPage(

            @ApiParam(name = "page", value = "页码", required = true)
            @RequestParam int page,
            @ApiParam(name = "limit", value = "查询条数", required = true)
            @RequestParam int limit, String unitName, Long startTime, String city, Integer grantType, Integer grantLevel, HttpSession session
    ) {

        return authorizationService.selectMyPage(page, limit, unitName, startTime, city, grantType, grantLevel, session);
    }

    /**
     * @param authorization
     * @return 机构信息删除
     */
    @RequestMapping(value = "authorizationDelete", method = RequestMethod.POST)
    @ResponseBody
    public Map authorizationDelete(@RequestBody Authorization authorization, HttpSession session) {
        Authorization a = authorizationService.getById(authorization.getId());
        File file = new File(a.getLogoUrl());
        if (file.isFile() && file.exists()) {
            file.delete();
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("grant_id",authorization.getId());
        List<AuthorizationImage> authorizationList = authorizationImageService.list(wrapper);
        for (int j = 0; j < authorizationList.size(); j++) {
            File file1 = new File(authorizationList.get(j).getUrl());
            if (file1.isFile() && file1.exists()) {
                file1.delete();
            }
        }
        if (getUser(session).getStatus() == 2) {
            if (authorizationService.removeById(authorization)) {
                if (authorizationImageService.removeByAuthorizationId(authorization.getId())) {
                    return ResponseUtil.getSuccessMap();
                }
            }
        } else {
            authorization.setType(2);
            authorization.setFlag(2);
            authorizationService.updateById(authorization);
            return ResponseUtil.getSuccessMap();
        }
        return ResponseUtil.getExceptionMap();
    }

    /**
     * @return 信息修改
     */
    @RequestMapping(value = "updateById", method = RequestMethod.POST)
    @ResponseBody
    public Map update(String param, String[] pIds,HttpSession session) {
        Authorization authorization = JSONObject.parseObject(param, Authorization.class);

        if (getUser(session).getStatus() == 2) {
            authorization.setType(1);
            authorization.setFlag(4);
            return authorizationService.updateAuthorization(authorization, pIds);
        } else {
            Authorization a = new Authorization();
            a.setUnitName(authorization.getUnitName());
            a.setStartTime(authorization.getStartTime());
            a.setEndTime(authorization.getEndTime());
            a.setCity(authorization.getCity());
            a.setGrantType(authorization.getGrantType());
            a.setGrantLevel(authorization.getGrantLevel());
            a.setBrief(authorization.getBrief());
            a.setLogoUrl(authorization.getLogoUrl());
            a.setBeforeId(authorization.getId());
            a.setFlag(3);
            a.setType(2);
            String arr = "";
            if (pIds[0].equals("kk")){
                List<AuthorizationImage> list = authorizationImageService.getByGrantId(authorization.getId());
                for (int i = 0; i <list.size() ; i++) {
                    AuthorizationImage authorizationImage = new AuthorizationImage();
                    authorizationImage.setUrl(list.get(i).getUrl());
                    authorizationImage.setCreateTime(DateUtil.date());
                    authorizationImageService.save(authorizationImage);
                    arr += authorizationImage.getId()+",";
                }
            }
            String[] split = arr.split(",");
            authorizationService.authorizationInsert(a,split);
            return ResponseUtil.getSuccessMap();
        }
    }

    /**
     * @return 授权机构查询通过单位名称
     */
    @RequestMapping(value = "authorization_select", method = RequestMethod.GET)
    @ResponseBody
    public List<Authorization> selectAuthorizationByUnitName(Authorization authorization) {
        return authorizationService.selectAuthorizationByUnitname(authorization);
    }


    //获取机构信息图片
    @RequestMapping("/getPhoto")
    public void getPhoto(HttpServletResponse response, @RequestParam("path") String path) throws Exception {
        System.out.println("path= " + path);
        File file = new File(path);
        FileInputStream fis;
        fis = new FileInputStream(file);
        long size = file.length();
        byte[] temp = new byte[(int) size];
        fis.read(temp, 0, (int) size);
        fis.close();
        byte[] data = temp;
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        out.write(data);
        out.flush();
        out.close();
    }

    /**
     * @param authorization
     * @return 机构登陆
     */
    @RequestMapping(value = "land", method = RequestMethod.POST)
    @ResponseBody
    public boolean login(Authorization authorization, HttpSession session1) {
        if (authorizationService.login(authorization, session1)) {
            return true;
        }
        return false;
    }

    /**
     * @param id
     * @return 机构图片回显--url
     */
    @RequestMapping(value = "getImageUrl", method = RequestMethod.POST)
    @ResponseBody
    public Map getImageUrl(String id) {
        Long grantId = (Long.parseLong(id));
        return authorizationService.getImageUrl(grantId);
    }

    /**
     * @param grantId
     * @return 多图片编辑
     * @throws Exception
     */
    @RequestMapping("/updatePicture")
    @ResponseBody
    public Massage updatePicture(String grantId, @RequestParam("file") MultipartFile file) {
        return authorizationImageService.updatePicture(grantId, file);
    }

    //批量删除
    @RequestMapping(value = "deleteBtId", method = RequestMethod.POST)
    @ResponseBody
    public Map deleteById(String ids,HttpSession sessions ) {
        String[] a = ids.split(",");
        for (int i = 1; i < a.length; i++) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("grant_id",a[i]);
            List<AuthorizationImage> authorizationList = authorizationImageService.list(wrapper);
            for (int j = 0; j < authorizationList.size(); j++) {
                File file1 = new File(authorizationList.get(j).getUrl());
                if (file1.isFile() && file1.exists()) {
                    file1.delete();
                }
            }
        }
        for (int i = 1; i < a.length; i++) {
            Authorization o = authorizationService.getById(a[i]);
            File  file = new File(o.getLogoUrl());
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        }

        if (getUser(sessions).getStatus() == 2) {
            for (int i = 1; i < a.length; i++) {
                authorizationService.removeById(a[i]);
                Authorization authorization = new Authorization();
                authorization.setId(Long.parseLong(a[i]));
                authorizationImageService.removeByAuthorizationId(authorization.getId());
            }
            return ResponseUtil.getSuccessMap();
        } else {
            for (int i = 1; i < a.length; i++) {
                Authorization authorization = new Authorization();
                authorization.setId(Long.parseLong(a[i]));
                authorization.setType(2);
                authorization.setFlag(2);
                authorizationService.updateById(authorization);
            }
            return ResponseUtil.getSuccessMap();

        }
    }

    /**
     * @param id
     * @return 回显地区
     */
    @RequestMapping(value = "getTeamCity", method = RequestMethod.POST)
    @ResponseBody
    public String getTeamCity(Long id) {
        return authorizationService.getTeamCity(id);
    }

    //通过
    @RequestMapping(value = "adopt", method = RequestMethod.POST)
    @ResponseBody
    public Map abopt(@RequestBody Authorization authorization) {
        Authorization a = authorizationService.getById(authorization);
        if (a.getFlag() == 2) {
            if (authorizationService.removeById(authorization) && authorizationImageService.removeByAuthorizationId(authorization.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        } else if (a.getFlag() == 1) {
            authorization.setType(1);
            authorization.setFlag(4);
            if (authorizationService.updateById(authorization)) {
                return ResponseUtil.getSuccessMap();
            }
        } else {
            authorization.setType(1);
            authorization.setFlag(4);
            authorizationService.updateById(authorization);
            if (authorizationService.removeById(a.getBeforeId()) && authorizationImageService.removeByAuthorizationId(a.getBeforeId())) {
                return ResponseUtil.getSuccessMap();
            }
        }
        return ResponseUtil.getExceptionMap();
    }

    //不通过
    @RequestMapping(value = "noAdopt", method = RequestMethod.POST)
    @ResponseBody
    public Map noAdopt(@RequestBody Authorization authorization) {
        Authorization a = authorizationService.getById(authorization);
        if (a.getFlag() == 2) {
            a.setFlag(4);
            a.setType(1);
            if (authorizationService.updateById(a)) {
                return ResponseUtil.getSuccessMap();
            }

        } else if (a.getFlag() == 1) {
            if (authorizationService.removeById(authorization) && authorizationImageService.removeByAuthorizationId(authorization.getId())) {

                return ResponseUtil.getSuccessMap();
            }
        } else {
            if (authorizationService.removeById(authorization) && authorizationImageService.removeByAuthorizationId(authorization.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        }

        return ResponseUtil.getExceptionMap();
    }
}
